// pages/bindingphone/bindingphone.js
var Ajax = require('../../utils/Ajax.js')
var utils = require('../../utils/util.js');
var app = getApp();
var iscode = true;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone: '', //手机号
    checkcode: '', //验证码
    referees: '',
    phoneshow: true,
    checkcodeshow: true,
    refereesshow: true,
    getcodebtn: true, //获取验证码按钮显示
    bindphone:false,
    yzmnum: 60,
    weChatInfo: {},
    userInfo: utils.getUserInfo()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var bindphone = options.bindphone==1 ? true:false;
    this.setData({
      bindphone,
      options,
      weChatInfo: utils.getWechatInfo(),
    })
    if (wx.setBackgroundColor) {
      wx.setBackgroundColor({
        backgroundColor: '#000', // 窗口的背景色为白色
      })
    }
  },
  //手机号输入框
  onbindValue(e) {
    var {
      name
    } = e.currentTarget.dataset;
    this.setData({
      [name]: e.detail.value
    })
  },
  oninpfocus(e) { //输入框获取焦点
    var inputname = e.target.dataset.name;
    this.setData({
      atv: inputname
    })
  },
  oninpblur(e) { //输入框失去焦点
    var inputname = e.target.dataset.name
    this.setData({
      atv: ''
    })
  },
  delText(e) { //清除按钮
    this.setData({
      ['' + e.detail]: ''
    })
  },
  //收不到验证码
  nocode(e) {
    this.showModal('nocode')
  },
  //获取验证码按钮
  getcode(e) {
    var that = this;
    var {
      phone
    } = this.data;
    if (phone.length != 11) {
      return utils.showtoast('手机号码为空或不正确');
    }
    var telcheck = utils.validatemobile(phone)
    if (telcheck && iscode) {
      iscode = false;
      Ajax.get('sendSms', {
        phone: phone
      }).then((d) => {
        if (d.status == 200) {
          this.countdown();
          utils.showtoast('验证码发送成功')
          this.setData({
            getcodebtn: false
          })
        } else {
          iscode = true;
          utils.showtoast(d.msg ||d.message ||d.data||'服务器异常,验证码发送失败')
        }
      }).catch((e) => {
        iscode = true;
        utils.showtoast('验证码发送失败,请检查您的网络')
      })
    } else {
      utils.showtoast('验证码已发送,请勿多次点击')
    }
  },
  countdown() {
    var sec = 60;
    for (var i = 0; i <= 60; i++) {
      setTimeout(() => {
        if (sec != 0) {
          sec--;
          this.setData({
            yzmnum: sec
          })
        } else {
          iscode = true;
          sec = 60; //如果倒计时结束就让  获取验证码显示出来
          this.setData({
            yzmnum: 60,
            getcodebtn: true
          })
        }
      }, i * 1000)
    }
  },
  //登录
  loginFn(e) {
    var tel = this.data.phone
    var telcheck = utils.validatemobile(tel)
    var {
      phone,
      checkcode,
      weChatInfo,
      bindphone
    } = this.data;
    if (telcheck) {
      var data = {
        unionId: app.getValueSync("unionId"),
        openId: app.getValueSync("openid"),
        phone: phone,
        nickName: weChatInfo && weChatInfo.userInfo && weChatInfo.userInfo.nickName || '',
        avatarUrl: weChatInfo && weChatInfo.userInfo && weChatInfo.userInfo.avatarUrl || '',
        code: checkcode,
      }
      utils.showLoading('登录中')
      Ajax.post('loginView', data).then((d) => {
        if (d.status == 200) {
          utils.hideLoading();
          this.setData({
            userInfo: d.data
          })
          app.saveSync('user_info', JSON.stringify(d.data));
          if (bindphone){
            wx.navigateBack()
          }else{
            this.getAllQuartersByUserId();
          }
        } else {
          utils.hideLoading();
          utils.showtoast(d.msg ||d.message|| '服务器错误,登录失败')
        }
      }).catch((e) => {
        console.log(e)
        utils.hideLoading();
        utils.showtoast('登录失败，请检查您的网络')
      })
    }
  },
  getAllQuartersByUserId() { //查询已认证的小区
    var {
      userInfo
    } = this.data;
    var lastopenId = app.getValueSync('lastopenId');
    Ajax.get("getAllQuartersByUserId", {
      userId: userInfo.id
    }).then((d) => {
      // 返回的小区列表为空  
      if (d.status == 200) {
        var currentQuarters = '';
        var list = d.data || [];
        for (let i = 0; i < list.length; i++) {
          if (lastopenId) {
            if (list[i].requId == lastopenId) {
              currentQuarters = list[i]
              break;
            }
          } else { //选择第一个小区
            currentQuarters = list[0];
            app.saveSync('lastopenId', currentQuarters.id)
            break;
          }
        }
        if (currentQuarters) {
          utils.showtoast('登录成功',null,null,true);
          setTimeout(()=>{
            wx.reLaunch({
              url: '/pages/index/index',
            })
          },1500)
        } else {
          var {options}=this.data;
          if (options.id){
            wx.redirectTo({
              url: `/pages/certification/certification?` + utils.queryconcat(options),
            })
          }else{
            wx.redirectTo({
              url: '/pages/seltelcommunity/seltelcommunity'
            })
          }
        }
      } else {
        utils.showtoast(d.message || '服务器出错')
      }
    }).catch((e) => {
      console.log(e)
    })
  },
  closeModal(id) { //关闭弹窗
    var modal = this.selectComponent("#" + (id || 'modal'));
    modal.hide();
  },
  //用户协议弹窗
  showText(e) {
    // console.log('showText')
    this.showModal('Agreement')
  },
  showModal(id) { //关闭弹窗
    // console.log(id)
    var modal = this.selectComponent("#" + id);
    console.log(modal)
    if (modal.isShow()) {
      modal.hide()
    } else {
      modal.show();
    }
  },
  //验证码错误重新填写
  restInput() {
    this.setData({
      checkcode: "",
    })
    this.showModal('codeErro')
  },
  onUnload: function() {

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // this.showModal('nocode')
  }
})